package org.takeback.chat.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.takeback.chat.entity.LHHModel;
import org.takeback.chat.entity.LHHNumDetail;
import org.takeback.chat.entity.LHHPlan;
import org.takeback.chat.entity.Message;
import org.takeback.chat.lottery.Lottery;
import org.takeback.chat.lottery.LotteryDetail;
import org.takeback.chat.store.room.Room;
import org.takeback.chat.utils.MessageUtils;
import org.takeback.chat.utils.NumberUtil;
import org.takeback.service.BaseService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.ImmutableMap;
@Service("gameG07Service")
public class GameG07Service extends BaseService {

	@Autowired
	LotteryService lotteryService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	private RoomService roomService;
	
	@Autowired
	private LHHPlanService lHHPlanService;
	@Autowired
	LHHNumDetailService lhhNumDetailService;
	
	
	//计算抢红包最后的结果
	@Transactional(rollbackFor = { Throwable.class })
	public void dealResult(Lottery lottery, Room room) {
		List<Integer> lastRedNum = lottery.getRedRandomLast(lottery.getId());
		
		//房间配置
		Map<String, Object> p = roomService.getRoomProperties("LHH0001");
		//获取所有
		List<LHHPlan> llList = this.dao.findByHql("from LHHPlan where roomId=:roomId and createTime < :lotteryCreateTime and status=1", ImmutableMap.of("roomId", room.getId(),"lotteryCreateTime", lottery.getCreateTime()));
		System.out.println("此次用户一共下了" + llList.size()+"单");
		for(LHHPlan lhh: llList) {
			String plan = lhh.getPlan();
			System.out.println(lhh.getUserId() + "的方案" + plan);
			System.out.println("开奖的结果" + lastRedNum.toString());
			LHHModel lhhModel = JSON.parseObject(plan, new TypeReference<LHHModel>() {});
			lhhModel.setP(p);
			Map<Integer, Integer> countMap = lHHPlanService.computedLash(lastRedNum);
			BigDecimal dzCount = lHHPlanService.dealDZRes2(lhhModel, countMap, p);
			System.out.println(lhh.getUserId() + "单注中的钱" + dzCount.doubleValue());
			//组合中的钱
			Map<String, BigDecimal>  tem  = lHHPlanService.dealZh(lhhModel, lastRedNum, p);
			System.out.println(lhh.getUserId() + "组合中的钱" + tem.get("countPeiQian"));
			BigDecimal lhhCount = lHHPlanService.dealLhh2(lhhModel, lastRedNum, p);
			System.out.println(lhh.getUserId() + "龙虎合中的钱" + lhhCount.doubleValue());
			
			BigDecimal all = dzCount.add(tem.get("countPeiQian")).add(lhhCount);
			System.out.println("用户一共中了：" + all.doubleValue());
			this.dao.executeUpdate("update PubUser a set a.money = COALESCE(a.money,0)+:money where a.id=:id",
					ImmutableMap.of("money", all.doubleValue(), "id", lhh.getUserId()));
			lhh.setStatus(0);
			lHHPlanService.update(LHHPlan.class, lhh);
		}
		LHHNumDetail lnd = new LHHNumDetail();
		lnd.setNum1(lastRedNum.get(0).toString());
		lnd.setNum2(lastRedNum.get(1).toString());
		lnd.setNum3(lastRedNum.get(2).toString());
		lnd.setNum4(lastRedNum.get(3).toString());
		lnd.setNum5(lastRedNum.get(4).toString());
		String str = "";
		if(lastRedNum.get(0) > lastRedNum.get(4)){
			 str = "龙";
		} else if(lastRedNum.get(0) < lastRedNum.get(4)) {
			 str = "虎";
		} else if(lastRedNum.get(0) == lastRedNum.get(4)){
			 str = "合";
		}
		lhhNumDetailService.save(LHHNumDetail.class, lnd);
		String msg = (new StringBuffer("此次红包尾数为:<span style='color:red;'>"+ lastRedNum.toString().replace("[", "").replace("]", "")+"</span><br> <span style='color:red;'>龙虎合为："+str+"</span>奖金分配完毕")).toString();
		MessageUtils.broadcastDelay(room, new Message("TXT_SYS", Integer.valueOf(0), msg, "888", lnd.toStr(), str));
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
		roomService.updateLHHConfig("2", "config_lhl_stop_or_start");
		Message msg2 = new Message();
		msg2.setContent("游戏开始，请开始押注！");
		msg2.setType(Message.TXT_SYS);
		MessageUtils.broadcast(room, msg2);
	}
	//计算抢红包最后的结果
	@Transactional(rollbackFor = { Throwable.class })
	public void dealResult1(Lottery lottery, Room room) {
		List<Integer> listLast = new ArrayList<Integer>();
		Map<Integer, LotteryDetail> lotteryDetailMap = lottery.getDetail();
		LotteryDetail last = null;
		LotteryDetail first = null;
		//得到5个位数
		for (Integer key : lotteryDetailMap.keySet()) {
			LotteryDetail temp = lotteryDetailMap.get(key);
			Integer tailPoint = NumberUtil.getTailPoint(lotteryDetailMap.get(key).getCoin());
			listLast.add(tailPoint);
			System.out.println("tailPoint= "+ tailPoint);
			if(last != null && last.getCreateDate().getTime() < temp.getCreateDate().getTime()) {
				last = temp;
			}
			if(first != null && first.getCreateDate().getTime() > first.getCreateDate().getTime()) {
				first = temp;
			}
			last = lotteryDetailMap.get(key);
			first = lotteryDetailMap.get(key);
		}
		
		//计算是龙虎还是合
		Integer lhhPoint = null;
		Integer lastPoint = NumberUtil.getTailPoint(last.getCoin());
		Integer firstPoint = NumberUtil.getTailPoint(last.getCoin());
		if(lastPoint > firstPoint) {
			lhhPoint = 1;
		} else if(lastPoint == firstPoint) {
			lhhPoint = 2;
		} else if(lastPoint < firstPoint) {
			lhhPoint = 3;
		}
		//获取所有
		List<LHHPlan> llList = this.dao.findByHql("from LHHPlan where roomId=:roomId and createTime < :lotteryCreateTime and status=1", ImmutableMap.of("roomId", room.getId(),"lotteryCreateTime", lottery.getCreateTime()));
//		List<String> planOne = 
		for(LHHPlan lhh: llList) {
////			方案一中的个数
//			int getPlanOnes = 0;
//			//方案一
//			Integer planOne = StringUtils.isNotBlank(lhh.getPlanOne()) ? null : Integer.parseInt(lhh.getPlanOne());
//			if(planOne != null) {
//				getPlanOnes = getPlanOneTimes(listLast, planOne);
//				if(getPlanOnes != 0) {
//					int plonePeiLv = getPays(room, getPlanOnes);
//					BigDecimal b1 = new BigDecimal(Double.toString(plonePeiLv));   
//					this.dao.executeUpdate("update PubUser a set a.money = COALESCE(a.money,0)+:money where a.id=:id",
//					ImmutableMap.of("money", lhh.getPlanOneMoney().multiply(b1).doubleValue(), "id", lhh.getUserId()));
//				}
//			}
//			//方案二
//			String planTwo = lhh.getPlanTwo();
//			if(StringUtils.isNotBlank(planTwo)) {
//				List<Integer> l = getPlanTwoToIntergerArr(planTwo);
//				int ptSize = l.size();
//				boolean isgetPt = listLast.containsAll(l);
//				if(isgetPt) {
//					int plonePeiLv = getPaysTwo(room, ptSize);
//					BigDecimal b1 = new BigDecimal(Double.toString(plonePeiLv));   
//					this.dao.executeUpdate("update PubUser a set a.money = COALESCE(a.money,0)+:money where a.id=:id",
//					ImmutableMap.of("money", lhh.getPlanTwoMoney().multiply(b1).doubleValue(), "id", lhh.getUserId()));
//				}
//			}
//			//方案三 
//			String planThree = lhh.getPlanThree();
//			if(StringUtils.isNotBlank(planThree)) {
//				List<Integer> lt = getPlanTwoToIntergerArr(planThree);
////				int ltSize = lt.size();
//				boolean isgetlt = lt.contains(lhhPoint);
//				if(isgetlt){
//					int planTPeiLv = getPaysThree(room, lhhPoint); //方案三对应的赔率
//					BigDecimal b1 = new BigDecimal(Double.toString(planTPeiLv));   
//					this.dao.executeUpdate("update PubUser a set a.money = COALESCE(a.money,0)+:money where a.id=:id",
//					ImmutableMap.of("money", lhh.getPlanThreeMoney().multiply(b1).doubleValue(), "id", lhh.getUserId()));
//				}
//			}
//			this.executeUpdate("update LHHPlan set status=0 where id=:id", ImmutableMap.of("id", lhh.getId()));
		}
		String msg = (new StringBuffer("此次红包尾数为:<span style='color:red;'>"+ listLast.toString()+"</span>奖金分配完毕")).toString();
		MessageUtils.broadcastDelay(room, new Message("TXT_SYS", Integer.valueOf(0), msg));
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
		roomService.updateLHHConfig("2", "config_lhl_stop_or_start");
		Message msg2 = new Message();
		msg2.setContent("游戏开始，请开始押注！");
		msg2.setType(Message.TXT_SYS);
		MessageUtils.broadcast(room, msg2);
	}
	
	//获取方案1对应倍数
	public int getPays(Room room, Integer times){
		String key = "config_D" + times.toString();
		Object pays = room.getProperties().get(key);
		if(pays == null) {
			throw new RuntimeException("缺少方案一赔率设置");
		}
		return (int) room.getProperties().get(key);
	}
	
	//获取方案2对应倍数
	public int getPaysTwo(Room room, Integer times){
		String key = "config_Z" + times.toString();
		Object pays = room.getProperties().get(key);
		if(pays == null) {
			throw new RuntimeException("缺少方案二赔率设置");
		}
		return (int) room.getProperties().get(key);
	}
	
	//获取方案1对应倍数
	public int getPaysThree(Room room, Integer times){
		String key = "";
		if(times == 1) {
			key = "config_L";
		} else if(times == 2) {
			key = "config_H";
		} else if(times == 2) {
			key = "config_LHH";
		}
		Object pays = room.getProperties().get(key);
		if(pays == null) {
			throw new RuntimeException("缺少方案三赔率设置");
		}
		return (int) room.getProperties().get(key);
	}
	
	public List<Integer> getPlanTwoToIntergerArr(String planTwo) {
		List<Integer> l = new ArrayList<Integer>();
		String[] arr = planTwo.split(",");
		for(String a : arr) {
			l.add(Integer.parseInt(a));
		}
		return l;
	}
	
	public int getPlanOneTimes(List<Integer> listLast, Integer a) {
		int i = 0; 
		for(Integer t : listLast) {
			if(t == a) i++; 
		}
		return i;
	}
}
